package com.yydlz.users.controller;

import com.auth0.jwt.interfaces.Claim;
import com.yydlz.users.service.JwtService;
import com.yydlz.users.service.UsersService;
import com.yydlz.users.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("jwt")
public class JwtController {
    @Resource
    public JwtService jwtService;

    @Autowired
    public UsersService usersService;

    @GetMapping("/getJwt")
    public Map<String, Object> getJwt(String code, HttpServletResponse response) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        //获取userId
        String userId = usersService.getUserId(code);
        String token = jwtService.getJwt(userId);

        // 创建一个 cookie对象
        Cookie cookie = new Cookie("token", token);
        //设置path为根路径，否则cookie只会返给/student路径
        cookie.setPath("/");
        //设置cookie过期时间-7天
        cookie.setMaxAge(7 * 24 * 60 * 60);
        //将cookie对象加入response响应
        response.addCookie(cookie);


        Map<String,Object> result = new HashMap<>();
        result.put("status", 1);
        result.put("msg","登录成功");
        result.put("token",token);
        return result;
    }

    @GetMapping("/verifyJwt")
    public Map<String,Object> verify(/*HttpServletRequest request*/@CookieValue(value = "token", defaultValue = "") String token){
        //前端将token放在HttpServletRequest请求头中传过来，在这里将token从中拿出来
        //String token = request.getHeader("token");

        Map<String,Object> map = new HashMap<>();

        try{
            map.put("status", true);
            map.put("msg", "正确token~~");
            //解析出用户id
            Claim userIdClaim = JWTUtils.verify(token).getClaim("userId");
            int userId= userIdClaim.asInt();
            map.put("userId",userId);//用户表id
        }catch (Exception e){
            e.printStackTrace();
            map.put("status", false);
            map.put("msg", "无效token~~");
        }

        return map;
    }
}
